package com.tanggh.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 
 * @author tanggaohong
 *
 */
public class CookieManager {
	
	public static final String USER_ID = "userId";

	private static CookieManager cookieManager;
	private CookieManager(){
		
	}
	
	public static CookieManager getInstance(){
		 if(null == cookieManager){
			 cookieManager = new CookieManager();
		 }
		 return cookieManager;
	}
	
	/**
	 * 添加一个值到cookis中
	 * @param response
	 * @param key
	 * @param value
	 */
	public void addCookis(HttpServletResponse response,String key,String value){
		Cookie c = new Cookie(key,value);
		c.setMaxAge(Integer.MAX_VALUE);//设置Cookie永久有效
		c.setPath("/");
		response.addCookie(c);
	}
	
	/**
	 * 根据key去value
	 * @param request
	 * @param key
	 * @return
	 */
	public String getValue(HttpServletRequest request,String key){
		Cookie[] cookies = request.getCookies();
		String value = null;
		if(null != cookies && cookies.length>0){
			for(Cookie c: cookies){
				if(c.getName().equals(key)){
					value = c.getValue();
					break ;
				}
			}
		}
		return value;
	}
	
	/**
	 * 根据key删除cookie
	 * @param response
	 * @param key
	 */
	public void removeCookie(HttpServletResponse response,String key){
		Cookie c = new Cookie(key,null);
		c.setMaxAge(0);//设置存活期为0，立即失效
		c.setPath("/");
		response.addCookie(c);
	}
}













